<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="题干" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectName">
              <a-input v-model="model.subjectName" placeholder="请输入题干"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="题型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectType">
              <j-dict-select-tag
                type="list"
                v-model="model.subjectType"
                dictCode="subject_type"
                placeholder="请选择题型"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="题目内容图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input v-model="model.subjectImage" placeholder="请输入题目内容图片"></a-input> -->
              <j-image-upload bizPath="scott/pic" v-model="model.subjectImage"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="所属知识点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectCourseId">
              <j-search-select-tag
                placeholder="请选择所属知识点"
                v-model="model.subjectCourseId"
                dict="course_knowledge,knowledge_name,id"
                :pageSize="6"
                :async="true"
              >
              </j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <!-- 题型是单选题或者多选题才有选项 -->
          <a-col :span="24" v-if="model.subjectType == '1' || model.subjectType == '2'">
            <a-form-model-item label="题目选项" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input v-model="model.subjectOption" placeholder="请输入题目选项"></a-input> -->
              <!-- 选项 -->
              <a-form-model-item label="A" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectOptionA">
                <a-input
                  v-model="model.subjectOptionA"
                  @change="subjectOptionChange"
                  placeholder="请输入A选项内容"
                ></a-input>
              </a-form-model-item>
              <a-form-model-item label="B" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectOptionB">
                <a-input
                  v-model="model.subjectOptionB"
                  @change="subjectOptionChange"
                  placeholder="请输入B选项内容"
                ></a-input>
              </a-form-model-item>
              <a-form-model-item label="C" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectOptionC">
                <a-input
                  v-model="model.subjectOptionC"
                  @change="subjectOptionChange"
                  placeholder="请输入C选项内容"
                ></a-input>
              </a-form-model-item>
              <a-form-model-item label="D" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectOptionD">
                <a-input
                  v-model="model.subjectOptionD"
                  @change="subjectOptionChange"
                  placeholder="请输入D选项内容"
                ></a-input>
              </a-form-model-item>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <!-- 如果题目类型是单选题，答案就提供一组单选按钮 -->
            <a-form-model-item
              label="答案"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="subjectAnswer"
              v-if="model.subjectType == '1'"
            >
              <a-radio-group v-model="model.subjectAnswer" @change="subjectAnswerRedioChange">
                <a-radio value='["A"]'> A </a-radio>
                <a-radio value='["B"]'> B </a-radio>
                <a-radio value='["C"]'> C </a-radio>
                <a-radio value='["D"]'> D </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 如果题目类型是多选题，答案就提供一组多选按钮 -->
            <a-form-model-item
              label="答案"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="subjectAnswerCheckbox"
              v-if="model.subjectType == '2'"
            >
              <a-checkbox-group @change="subjectAnswerCheckboxChange" v-model="model.subjectAnswerCheckbox">
                <a-checkbox value="A"> A </a-checkbox>
                <a-checkbox value="B"> B </a-checkbox>
                <a-checkbox value="C"> C </a-checkbox>
                <a-checkbox value="D"> D </a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>
            <!-- 如果题目类型是判断题，也直接整一组单选框 -->
            <a-form-model-item
              label="答案"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="subjectAnswer"
              v-if="model.subjectType == '3'"
            >
              <a-radio-group
                v-model="model.subjectAnswer"
                @change="subjectAnswerRedioChange"
                v-if="model.subjectType == '3'"
              >
                <a-radio value='["true"]'> 正确 </a-radio>
                <a-radio value='["false"]'> 错误 </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 填空题答案 v-if="model.subjectType == '4'" -->
            <template v-if="model.subjectType == '4'">
              <a-form-model-item
                v-for="(domain, index) in model.domains"
                :key="domain.key"
                v-bind="index === 0 ? formItemLayout : {}"
                :label="'空' + (index + 1) + '答案'"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                :prop="domains"
                :rules="{
                  required: true,
                  message: '请输入答案',
                  trigger: 'blur',
                }"
              >
                <a-input
                  v-model="domain.value"
                  @change="domainChange"
                  placeholder="请输入答案项内容"
                  style="width: 60%; margin-right: 8px"
                />
                <a-icon
                  v-if="model.domains.length > 1"
                  class="dynamic-delete-button"
                  type="minus-circle-o"
                  :disabled="model.domains.length === 1"
                  @click="removeDomain(domain)"
                />
              </a-form-model-item>
              <a-form-model-item v-bind="formItemLayoutWithOutLabel">
                <a-button type="dashed" style="width: 60%" @click="addDomain">
                  <a-icon type="plus" /> 添加填空题答案项
                </a-button>
              </a-form-model-item>
            </template>
            <!-- 结束 -->
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="题目难度1-5递增难度"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="subjectDifficulty"
            >
              <a-input-number
                v-model="model.subjectDifficulty"
                placeholder="请输入题目难度"
                style="width: 100%"
                :max="5"
                :min="1"
                :step="1"
                :formatter="limitNumber"
                :parser="limitNumber"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="题目解析" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectAnalysis">
              <!-- <a-input v-model="model.subjectAnalysis" placeholder="请输入题目解析"></a-input> -->
              <j-editor v-model="model.subjectAnalysis" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'SubjectForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      // 填空题的答案项数据
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 },
        },
      },

      // 题目的选项
      subjectOption: {},
      model: {
        domains: [],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        subjectName: [{ required: true, message: '请输入题干!' }],
        subjectType: [
          {
            required: true,
            message: '请输入题型',
          },
        ],
        subjectCourseId: [{ required: true, message: '请输入所属知识点!' }],
        // subjectOption: [{ required: true, message: '请填写完整选项内容' }],
        subjectOptionA: [{ required: true, message: '请输入A选项内容' }],
        subjectOptionB: [{ required: true, message: '请输入B选项内容' }],
        subjectOptionC: [{ required: true, message: '请输入C选项内容' }],
        subjectOptionD: [{ required: true, message: '请输入D选项内容' }],
        subjectAnswer: [{ required: true, message: '请输入答案' }],
        subjectAnswerCheckbox: [{ required: true, message: '请选择答案' }],
        subjectDifficulty: [{ required: true, message: '请输入题目难度' }],
        subjectAnalysis: [{ required: true, message: '请输入题目解析!' }],
      },
      url: {
        add: '/subject/subject/add',
        edit: '/subject/subject/edit',
        queryById: '/subject/subject/queryById',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    // // 休眠的方法
    sleep(n) {
      var start = new Date().getTime()
      while (true) {
        if (new Date().getTime() - start > n) {
          break
        }
      }
    },
    // 选择题选项的组件刷新
    subjectOptionChange() {
      this.$forceUpdate()
    },
    // 填空题答案项的组件刷新
    domainChange() {
      this.$forceUpdate()
    },
    // 填空题答案项有关方法
    removeDomain(item) {
      let index = this.model.domains.indexOf(item)
      if (index !== -1) {
        this.model.domains.splice(index, 1)
      }
      // 刷新填空题答案项输入框
      this.$forceUpdate()
    },
    addDomain() {
      console.log(this.model.domains)
      // 初始化数组
      if (this.model.domains == null) {
        this.model.domains = []
      }
      this.model.domains.push({
        value: '',
        key: Date.now(),
      })
      // 刷新填空题答案项输入框
      this.$forceUpdate()
    },

    // 正则替换小数点
    limitNumber(value) {
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(/[^0-9]/g, '') : 1
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(/[^0-9]/g, '') : 1
      } else {
        return 1
      }
    },
    // 题目答案单选框改变事件
    subjectAnswerRedioChange() {
      // 为了避免做一个json的转换单选题:[“A”]，我们单选框的value值直接整成需要的格式
      console.log(this.model.subjectAnswer)
    },
    //题目答案多选框的改变事件
    subjectAnswerCheckboxChange(checkedValues) {
      console.log(checkedValues)
      this.$forceUpdate()
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      //如果是新增，那么就没有id，修改的话，就需要拿到数据，然后对json进行转对象的处理
      if (this.model.id != null) {
        console.log('编辑的对象：')
        console.log(this.model)
        // json转对象的处理
        // 多选题或者判断题都需要对选项进行处理
        if (this.model.subjectType == '2' || this.model.subjectType == '1') {
          var subjectOptions = JSON.parse(this.model.subjectOption)
          subjectOptions.forEach((element) => {
            if (element.option === 'A') {
              this.model.subjectOptionA = element.content
            } else if (element.option === 'B') {
              this.model.subjectOptionB = element.content
            } else if (element.option === 'C') {
              this.model.subjectOptionC = element.content
            } else if (element.option === 'D') {
              this.model.subjectOptionD = element.content
            }
          })
        }
        // 填空题需要对答案做一个json转换数组的处理
        if (this.model.subjectType == '4') {
          // this.model.domains = JSON.parse(this.model.subjectAnswer)
          var array = JSON.parse(this.model.subjectAnswer)
          console.log(array)
          this.model.domains = []

          array.forEach((element) => {
            this.model.domains.push({
              value: element,
              key: new Date().getTime(),
            })
            // 休眠1毫秒，虽然这个方法是靠烧cpu不推荐，但是没有找到替代的方法
            this.sleep(1)
          })
        }
        var subjectAnswerCheckbox = JSON.parse(this.model.subjectAnswer)
        this.model.subjectAnswerCheckbox = subjectAnswerCheckbox
      }
      this.visible = true
    },
    // 表单提交事件
    submitForm() {
      //将选择题(单选题和多选题才有题目选项)的选项进行处理，把对象转换成json字符串
      // [{“option”:”A”,” content”:”xxxxxx”},{“option”:”B”,” content”:”xxxxxx”}]
      if (this.model.subjectType == '1' || this.model.subjectType == '2') {
        function SubjectOption(option, content) {
          this.option = option
          this.content = content
        }
        var subjectOptions = []
        subjectOptions.push(new SubjectOption('A', this.model.subjectOptionA))
        subjectOptions.push(new SubjectOption('B', this.model.subjectOptionB))
        subjectOptions.push(new SubjectOption('C', this.model.subjectOptionC))
        subjectOptions.push(new SubjectOption('D', this.model.subjectOptionD))
        this.model.subjectOption = JSON.stringify(subjectOptions)
        console.log('答案选项：' + this.model.subjectOption)
        if (this.model.subjectType == '2') {
          this.model.subjectAnswer = JSON.stringify(this.model.subjectAnswerCheckbox)
        }
      } else if (this.model.subjectType == '4') {
        // 填空题没有题目选项
        this.model.subjectOption = null
        //填空题需要对答案进行处理
        var answerArray = new Array()
        this.model.domains.forEach((element) => {
          // 我们只要value
          answerArray.push(element.value)
        })
        this.model.subjectAnswer = JSON.stringify(answerArray)
      } else if (this.model.subjectType == '5') {
        // 简答题没有题目选项，也没有答案
        this.model.subjectOption = null
        this.model.subjectAnswer = null
      }
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>
<style>
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>